package com.liu.gateway.gateway.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.RandomUtil;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author lxh
 * @date 2018/2/9
 */
@Slf4j
@RestController
public class CaptchaController {

    @Value("${captcha-expiry-time}")
    private Integer captchaExpiryTime;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/captcha")
    public Object captcha() {
        try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            //获取4位随机数字
            String code = RandomUtil.randomNumbers(4);
            String uuid = cn.hutool.core.lang.UUID.randomUUID().toString();
            //放入redis 过去时间设置为60秒
            log.info("数字验证码：captchakey:"+uuid+",验证码：captcha："+code);
            stringRedisTemplate.boundValueOps(uuid).set(code,captchaExpiryTime, TimeUnit.SECONDS);
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 50);
            Image image = lineCaptcha.createImage(code);
            // 获取 Image 对象的高度和宽度
            int width = image.getWidth(null);
            int height = image.getHeight(null);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.getGraphics();
            //通过 BufferedImage 绘制图像并保存在其对象中
            g.drawImage(image, 0, 0, width, height, null);
            g.dispose();
            //转换流
            ImageIO.write(bi,"png",baos);
            String imgBase64 = Base64.encodeBase64String(baos.toByteArray());
            return ResponseEntity.ok()
                    .header("Access-Control-Allow-Origin","*")
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(
                            ImmutableMap.of("data", ImmutableMap.of(uuid,"data:image/jpeg;base64,"+imgBase64)
                                    ,"captchaKey",uuid   //存储在redis中的key
                                    ,"code", 200
                                    ,"msg", "成功！"
                                    ,"timestamp", System.currentTimeMillis())
                    );
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
    }
}
